# encoding=utf-8

import time, threading
import config, instruction, utils
from bot import Bot

def prepare(bot):
    # 关闭所有聊天频道
    bot.send_ins(instruction.ins_talk_switch())
    
def complish_newguide(bot):
    # 完成新手任务
    ins = instruction.ins_newguide()
    for c in ins:
        bot.send_ins([c])
        time.sleep(0.1)

def main(uname, pwd):
    bot = Bot(config.regsi_server, uname, pwd)
    
    bot.set_prepare(prepare)
    bot.set_task(complish_newguide, 1, 1)

    if bot.register():
        # 注册成功，开始登录
        bot.set_addr(config.login_server)
        if bot.login():
            bot.sync_start()
        else:
            print '注册+登录都失败，账号名密码错误；该账号不可用'
    else:
        # 注册失败，尝试登录
        print '注册失败, 尝试登录...'
        bot.set_addr(config.login_server)
        state = bot.login()
        if state == 'LOGIN_NEWGUIDE':
            bot.sync_start()
        elif state == True:
            print '登录成功，该账号已经完成注册'
    
    print '[%s][%s] 已完成注册和新手引导' % (bot.username, bot.password)

class RegisterBot(threading.Thread):
    def __init__(self, lock, threadName, userdata):
        super(RegisterBot, self).__init__(name=threadName)
        self.lock = lock
        self.userdata = userdata

    def notice_end(self):
        global now
        self.lock.acquire()
        now += 1
        self.lock.release()

    def run(self):
        main(userdata['username'], userdata['password'])
        self.notice_end()
        print '[%s] has end' % self.name

need = 100
now  = 0
lock = threading.Lock()
for i in range(now, need):
    userdata = {'username': 'minerbott' + str(i),
                'password': '123456'}
    RegisterBot(lock, 'thread-' + str(i), userdata).start()
    #main(userdata['username'], '123456')


while True:
    lock.acquire()
    print '%d/%d' % (now, need)
    if now == need:
        lock.release()
        break
    lock.release()
    time.sleep(0.1)

print '[*] All bot has accomplish!!!!'
